package com.alan.netty.nio.buffers;

import java.nio.Buffer;
import java.nio.ByteBuffer;

/**
 * @author weiBin
 * @date 2018/11/7
 */
public class BufferCreate {
    /**
     * 缓存区创建的方式
     * ByteBuffer.allocateDirect(10);
     * ByteBuffer.allocate(10);
     * ByteBuffer.warp(byte[]);
     */
    public static void main(String[] args) {
        ByteBuffer buffer1 = ByteBuffer.allocate(10);
        printBuffer(buffer1);
        ByteBuffer buffer2 = ByteBuffer.allocateDirect(10);
        if (buffer2.isDirect()) {
            printBuffer(buffer2);
        }
        byte[] bytes = "hello world".getBytes();
        ByteBuffer buffer3 = ByteBuffer.wrap(bytes);
        printBuffer(buffer3);
        //创建缓存区后指定偏移和取值长度 limit = length + offset
        ByteBuffer buffer4 = ByteBuffer.wrap(bytes, 2, 5);
        printBuffer(buffer4);
        buffer4.position(buffer4.limit());
        buffer4.flip();
        while (buffer4.hasRemaining()) {
            System.out.println(buffer4.get());
        }
    }

    private static void printBuffer(Buffer buffer) {
        System.out.println("[limit=" + buffer.limit()
                + ", position = " + buffer.position()
                + ", capacity = " + buffer.capacity()
                + ",remaining =" + buffer.remaining()
                + ",hasArray =" + buffer.hasArray()
                + ",isDirect =" + buffer.isDirect()
                + ",isReadOnly =" + buffer.isReadOnly()
                + ", array = " + buffer.toString() + "]");
    }
}
